Optimization is important in many fields, including in data science. In manufacturing, where every decision is critical to the process and the profit of organization, optimization is often employed, from the number of each products produced, how the unit is scheduled for production, get the best or optimal process parameter, and also the routing determination such as the traveling salesman problem. In data science, we are familiar with model tuning, where we tune our model in order to improve the model performance. Optimization algorithm can help us to get a better model performance.
Bayesian Optimization is one of many optimization algorithm that can be employed to various cases. Bayesian Optimization employ a probabilistic model to optimize the fitness function. The advantage of Bayesian Optimization is when evaluations of the fitness function are expensive to perform — as is the case when it requires training a machine learning algorithm — it is easy to justify some extra computation to make better decisions1. It is best-suited for optimization over continuous domains of less than 20 dimensions, and tolerates stochastic noise in function evaluations2.
This post is dedicated to learn how Bayesian Optimization works and their application in various business and data science case. The algorithm will be run in R.
The general procedure when works with Bayesian Optimization is as follows:
Bayesian Optimization consists of two main components: a Bayesian statistical model for modeling the objective function, and an acquisition function for deciding where to sample next. The Gaussian process is often employed for the statistical model due to its flexibility and tractability.
The model used for approximating the objective function is called surrogate model. Gaussian process is one of them. Whenever we have an unknown value in Bayesian statistics, we suppose that it was drawn at random by nature from some prior probability distribution. Gaussian Process takes this prior distribution to be multivariate normal, with a specific mean vector and covariance matrix.
The prior distribution on \([f(x_1), f(x_2), ..., f(x_k)]\) is:
\[f(x_{1:k}) \sim \mathcal{N} (\mu_0(x_{1:k}),\ \Sigma_0(x_{1:k}, x_{1:k})) \]
\(\mathcal{N}(x,y)\) : Gaussian/Normal random distribution
\(\mu_0(x_{i:k})\) : Mean function of each \(x_i\). It is common to use \(m(x)=0\) as Gaussian Process is flexible enough to model the mean arbitrarily well3
\(\Sigma_0(x_{i:k},x_{i:k})\) : Kernel function/covariance function at each pair of \(x_i\)
Gaussian process also provides a Bayesian posterior probability distribution that describes potential values for \(f(x)\) at the candidate point \(x\). Each time we observe f at a new point, this posterior distribution is updated. The Gaussian process prior distribution can be converted into posterior distirbution after having some observed some \(f\) or \(y\) values.
\[f(x)|f(x_{1:n}) \sim \mathcal{N} (\mu_n(x), \ \sigma_n^2(x))\]
Where:
\[\mu_n(x) = \Sigma_0(x,x_{i:n}) * \Sigma_0(x_{i:n},x_{i:n})^{-1} * (f(x_{1:n})-\mu_0(x_{1:n})) + \mu_0(x)\]
\[\sigma_n^2(x) = \Sigma_0(x,x) - \Sigma_0(x,x_{i:n}) * \Sigma_0(x_{i:n},x_{i:n})^{-1} * \Sigma_0(x_{i:n},x)\]
Below is the example of Gaussian Process posterior over function graph. The blue dot represent the fitness function of 3 sample points. The solid red line represent the estimate of the fitness function while the dashed line represent the Bayesian credible intervals (similar to confidence intervals).
Let’s illustrate the process with GPfit package. Suppose I have a function below:
Create noise-free \(f\) for \(n_0\) based on 5 points within range of [0,1].
## x y
## [1,] 0.0000000 75.68025
## [2,] 0.3333333 32.59273
## [3,] 0.5000000 -43.46241
## [4,] 0.6666667 -74.99929
## [5,] 1.0000000 17.33797
Create a gaussian process with GP_fit() with power exponential correlation function. You can also use Matern correlation function list(type = "matern", nu = 5/2)4.
After we fitted GP model, we can calculate the expected value \(μ(x)\) at each possible value of x and the corresponding uncertainty \(σ(x)\). These will be used when computing the acquisition functions over the possible values of x.
x_new <- seq(0, 1, length.out = 100)
pred <- predict.GP(fit, xnew = data.frame(x = x_new))
mu <- pred$Y_hat
sigma <- sqrt(pred$MSE)We can visualize the result.
ggplot(as.data.frame(eval))+
geom_line(data = data.frame(x = x_new, y = mu),
aes(x = x, y = y), color = "red", linetype = "dashed")+
geom_ribbon(data = data.frame(x = x_new, y_up = mu + sigma, y_low = mu - sigma),
aes(x = x_new, ymax = y_up, ymin = y_low), fill = "skyblue", alpha = 0.5) +
geom_point(aes(x,y), size = 2)+
theme_minimal() +
labs(title = "Gaussian Process Posterior of f(x)",
subtitle = "Blue area indicate the credible intervals",
y = "f(x)")Acquisition function is employed to choose which point of \(x\) that we will take the sample next. The chosen point is those with the optimum value of acquisition function. The acquisition function calculate the value that would be generated by evaluation of the fitness function at a new point \(x\), based on the current posterior distribution over \(f\).
Below is the illustration of the acquisition function value curve. The value is calculated using expected improvement method. Point with the highest value of the acquisition function will be sampled at the next round/iteration.
There are several choice of acquisition function, such as expected improvement, Gaussian Process upper confidence bound, entropy search, etc. Here we will illustrate the expected improvement function.
\[EI(x) = \left\{ \begin{array}{ll} (\mu(x) - f(x^+) - \xi) \Phi(Z) + \sigma(x) \phi(Z) & if \ \sigma(x) > 0 \\ 0 & if \ \sigma(x) = 0 \\ \end{array} \right. \]
Where
\[Z = \frac{\mu(x) - f(x^+) - \xi}{\sigma(x)}\]
\(f(x^+)\) : Best value of \(f(x)\) of the sample
\(\mu(x)\) : Mean of the GP posterior predictive at \(x\)
\(\sigma(x)\) : Standard deviation of the GP posterior predictive at \(x\)
\(\xi\) : xi(some call epsilon instead). Determines the amount of exploration during optimization and higher ξ values lead to more exploration. A common default value for ξ is 0.01.
\(\Phi\) : The cumulative density function (CDF) of the standard normal distribution
\(\phi\) : The probability density function (PDF) of the standard normal distribution
Suppose that y_best is the best fitness value from the sample
We can use the code below to get the expected improvement value for each x. We will use epsilon value of 0.01.
eps <- 0.01
ei_calc <- function(m, s) {
if (s == 0) {
return(0)
}
Z <- (m - y_best - eps)/s
expected_imp <- (m - y_best - eps) * pnorm(Z) + s * dnorm(Z)
return(expected_imp)
}
expected_improvement <- numeric()
for (i in 1:length(mu)) {
expected_improvement[i] <- ei_calc(m = mu[i],s = sigma[i])
}Let’s visualize the result. Create data.frame for the result and create exp_best which consists of x with the highest expected improvement value.
exp_imp <- data.frame(x = x_new,
y = expected_improvement)
exp_best <- exp_imp %>% filter(y == max(y))We can visualize the result
ggplot(exp_imp, aes(x, y))+
geom_line()+
geom_ribbon(aes(ymin = 0, ymax = y), fill = "skyblue", alpha = 0.5, color = "white")+
geom_vline(xintercept = exp_best$x, linetype = "dashed", color = "red")+
geom_point(data = exp_best, size = 2)+
theme_minimal() +
theme(panel.grid = element_blank())+
scale_x_continuous(breaks = c(seq(0,1,0.25), round(exp_best$x,2)))+
labs(title = "Expected Improvement",
subtitle = "x with the highest expected improvement will be evaluated",
y = "Expected Improvement")With this basic steps, I hope we are ready to apply Bayesian Optimization.
We can do Bayesian optimization in R using rBayesianOptimization package.
The problem is replicated from Zhu et al.(2011)5. The study employed a PSO algorithm for portfolio selection and optimization in investment management.
Portfolio optimization problem is concerned with managing the portfolio of assets that minimizes the risk objectives subjected to the constraint for guaranteeing a given level of returns. One of the fundamental principles of financial investment is diversification where investors diversify their investments into different types of assets. Portfolio diversification minimizes investors exposure to risks, and maximizes returns on portfolios.
The fitness function is the adjusted Sharpe Ratio for restricted portofolio, which combines the information from mean and variance of an asset and functioned as a risk-adjusted measure of mean return, which is often used to evaluate the performance of a portfolio.
The Sharpe ratio can help to explain whether a portfolio’s excess returns are due to smart investment decisions or a result of too much risk. Although one portfolio or fund can enjoy higher returns than its peers, it is only a good investment if those higher returns do not come with an excess of additional risk.
The greater a portfolio’s Sharpe ratio, the better its risk-adjusted performance. If the analysis results in a negative Sharpe ratio, it either means the risk-free rate is greater than the portfolio’s return, or the portfolio’s return is expected to be negative.
The fitness function is shown below:
\[Max \ f(x) = \frac{\sum_{i=1}^{N} W_i*r_i - R_f}{\sum_{i=1}^{N}\sum_{j=1}^{N} W_i * W_j * \sigma_{ij}}\]
Subject To
\[\sum_{i=1}^{N} W_i = 1\] \[0 \leq W_i \leq 1\] \[i = 1, 2, ..., N\]
\(N\): Number of different assets
\(W_i\): Weight of each stock in the portfolio
\(r_i\): Return of stock i
\(R_f\): The test available rate of return of a risk-free security (i.e. the interest rate on a three-month U.S. Treasury bill)
\(\sigma_{ij}\): Covariance between returns of assets i and j,
Adjusting the portfolio weights \(w_i\), we can maximize the portfolio Sharpe Ratio in effect balancing the trade-off between maximizing the expected return and at the same time minimizing the risk.
Data is acquired from New York Stock Exchange on Kaggle (https://www.kaggle.com/dgawlik/nyse). We will only use data from January to March of 2015 for illustration.
nyse <- data.table::fread("data_input/prices.csv")
nyse <- nyse %>%
mutate(date = ymd(date)) %>%
filter(year(date) == 2015,
month(date) %in% c(1:3))
head(nyse)To get clearer name of company, let’s import the Ticker Symbol and Security.
securities <- data.table::fread("data_input/securities.csv")
securities <- securities %>%
select(`Ticker symbol`, Security) %>%
rename(stock = `Ticker symbol`)Let’s say I have assets in 3 different stocks. I will randomly choose the stocks.
set.seed(13)
selected_stock <- sample(nyse$symbol, 3)
nyse <- nyse %>%
filter(symbol %in% selected_stock)
head(nyse)Let’s calculate the daily returns.
nyse <- nyse %>%
select(date, symbol, close) %>%
group_by(symbol) %>%
rename(price = close) %>%
mutate(price_prev = lag(price),
returns = (price - price_prev)/price_prev) %>%
slice(-1) %>%
ungroup()
head(nyse)Let’s calculate the mean return of each stock.
The value of \(R_f\) is acquired from the latest interest rate on a three-month U.S. Treasury bill. Since the data is from 2016, we will use data from 2015 (Use data from March 27, 2015), which is 0.04%. The rate is acquired from https://ycharts.com/indicators/3_month_t_bill.
Calculate the covariance matrix between portofolio. First, we need to separate the return of each portofolio into several column by spreading them.
nyse_wide <- nyse %>%
pivot_wider(id_cols = c(date, symbol), names_from = symbol, values_from = returns) %>%
select(-date)
# Create Excess Return
for (i in 1:n_distinct(nyse$symbol)) {
nyse_wide[,i]<- nyse_wide[,i] - as.numeric(mean_stock[i,2])
}
head(nyse_wide)Create the covariance matrix.
Let’s define the fitness function. We will penalize the solution that violate the constraint. Higher penalty will increases accuracy and force the fitness value to get closer to the feasible area.
fitness <- function(w1,w2,w3){
# Assign weight for each stocks
weight_stock <- c(w1,w2,w3)
# Calculate the numerator
f1 <- numeric()
for (i in 1:n_distinct(nyse$symbol)) {
f1[i] <- weight_stock[i]*mean_stock$mean[i]
}
# Calculate the denominator
f2 <- numeric()
for (i in 1:n_distinct(nyse$symbol)) {
f3 <- numeric()
for (j in 1:n_distinct(nyse$symbol)) {
f3[j] <- weight_stock[i]*weight_stock[j]*nyse_cov[i,j]
}
f2[i] <- sum(f3)
}
# Calculate Fitness Value
fitness <- (sum(f1)-rf)/sum(f2)
# Penalize Constraint Violation
fitness <- fitness - 1e9 * (round(sum(weight_stock),10)-1)^2
result <- list(Score = fitness, Pred = 0)
return(result)
}Let’s define the search boundary
Let’s set the initial sample
set.seed(123)
search_grid <- data.frame(w1 = runif(20,0,1),
w2 = runif(20,0,1),
w3 = runif(20,0,1))
head(search_grid)Use BayesianOptimization() function to employ the algorithm. The parameters include:
set.seed(1)
tictoc::tic()
bayes_finance <- BayesianOptimization(FUN = fitness, bounds = search_bound,
init_grid_dt = search_grid, init_points = 0,
n_iter = 10, acq = "ei")## elapsed = 0.04 Round = 1 w1 = 0.2876 w2 = 0.8895 w3 = 0.1428 Value = -102346787.3517
## elapsed = 0.00 Round = 2 w1 = 0.7883 w2 = 0.6928 w3 = 0.4145 Value = -802197653.5235
## elapsed = 0.00 Round = 3 w1 = 0.4090 w2 = 0.6405 w3 = 0.4137 Value = -214561698.7466
## elapsed = 0.00 Round = 4 w1 = 0.8830 w2 = 0.9943 w3 = 0.3688 Value = -1552846530.5179
## elapsed = 0.00 Round = 5 w1 = 0.9405 w2 = 0.6557 w3 = 0.1524 Value = -560428652.5203
## elapsed = 0.00 Round = 6 w1 = 0.0456 w2 = 0.7085 w3 = 0.1388 Value = -11471892.0673
## elapsed = 0.02 Round = 7 w1 = 0.5281 w2 = 0.5441 w3 = 0.2330 Value = -93150457.4806
## elapsed = 0.00 Round = 8 w1 = 0.8924 w2 = 0.5941 w3 = 0.4660 Value = -907301041.4723
## elapsed = 0.00 Round = 9 w1 = 0.5514 w2 = 0.2892 w3 = 0.2660 Value = -11356600.7449
## elapsed = 0.00 Round = 10 w1 = 0.4566 w2 = 0.1471 w3 = 0.8578 Value = -213034020.6426
## elapsed = 0.00 Round = 11 w1 = 0.9568 w2 = 0.9630 w3 = 0.0458 Value = -932554747.0758
## elapsed = 0.00 Round = 12 w1 = 0.4533 w2 = 0.9023 w3 = 0.4422 Value = -636537927.4026
## elapsed = 0.00 Round = 13 w1 = 0.6776 w2 = 0.6907 w3 = 0.7989 Value = -1362357606.0057
## elapsed = 0.00 Round = 14 w1 = 0.5726 w2 = 0.7955 w3 = 0.1219 Value = -240100071.0720
## elapsed = 0.00 Round = 15 w1 = 0.1029 w2 = 0.0246 w3 = 0.5609 Value = -97040726.7633
## elapsed = 0.00 Round = 16 w1 = 0.8998 w2 = 0.4778 w3 = 0.2065 Value = -341233940.9660
## elapsed = 0.00 Round = 17 w1 = 0.2461 w2 = 0.7585 w3 = 0.1275 Value = -17444831.2329
## elapsed = 0.00 Round = 18 w1 = 0.0421 w2 = 0.2164 w3 = 0.7533 Value = -138639.9912
## elapsed = 0.01 Round = 19 w1 = 0.3279 w2 = 0.3182 w3 = 0.8950 Value = -292840156.2228
## elapsed = 0.00 Round = 20 w1 = 0.9545 w2 = 0.2316 w3 = 0.3745 Value = -314263621.5192
## elapsed = 0.00 Round = 21 w1 = 0.9749 w2 = 0.0000 w3 = 0.0000 Value = -627666.4709
## elapsed = 0.00 Round = 22 w1 = 0.0000 w2 = 0.0000 w3 = 1.0000 Value = 16.2381
## elapsed = 0.00 Round = 23 w1 = 0.7114 w2 = 0.0000 w3 = 0.2841 Value = -20886.1637
## elapsed = 0.00 Round = 24 w1 = 0.0000 w2 = 0.9980 w3 = 0.0000 Value = -4032.3122
## elapsed = 0.00 Round = 25 w1 = 0.7790 w2 = 0.1572 w3 = 0.0581 Value = -33160.3833
## elapsed = 0.00 Round = 26 w1 = 0.0076 w2 = 0.4095 w3 = 0.5954 Value = -157505.4064
## elapsed = 0.00 Round = 27 w1 = 0.0000 w2 = 0.5964 w3 = 0.4066 Value = -9006.5778
## elapsed = 0.00 Round = 28 w1 = 0.0020 w2 = 0.8404 w3 = 0.1630 Value = -28718.3692
## elapsed = 0.00 Round = 29 w1 = 0.1507 w2 = 0.0048 w3 = 0.8444 Value = -21.0078
## elapsed = 0.00 Round = 30 w1 = 0.0781 w2 = 0.0000 w3 = 0.9129 Value = -80038.9236
##
## Best Parameters Found:
## Round = 22 w1 = 0.0000 w2 = 0.0000 w3 = 1.0000 Value = 16.2381
## 98.28 sec elapsed
Result of the function consists of a list with 4 components:
So, what is the optimum Sharpe Ratio from Bayesian optimization?
## [1] 16.23812
The greater a portfolio’s Sharpe ratio, the better its risk-adjusted performance. If the analysis results in a negative Sharpe ratio, it either means the risk-free rate is greater than the portfolio’s return, or the portfolio’s return is expected to be negative.
Let’s check the total weight of the optimum result.
## [1] 1
Based on Bayesian Optimization, here is how your asset should be distributed.
data.frame(stock = unique(nyse$symbol),
weight = bayes_finance$Best_Par) %>%
arrange(desc(weight)) %>%
mutate(weight = percent(weight, accuracy = 0.01)) %>%
left_join(securities, by = "stock") %>%
select(stock, Security, weight)Let’s try another Bayesian Optimization for the problem. We will change the acquisition function from expected improvement to Gaussian Process upper confidence limit.
set.seed(1)
tictoc::tic(1)
bayes_finance <- BayesianOptimization(FUN = fitness, bounds = search_bound,
init_grid_dt = search_grid, init_points = 0,
n_iter = 10, acq = "ucb")## elapsed = 0.00 Round = 1 w1 = 0.2876 w2 = 0.8895 w3 = 0.1428 Value = -102346787.3517
## elapsed = 0.00 Round = 2 w1 = 0.7883 w2 = 0.6928 w3 = 0.4145 Value = -802197653.5235
## elapsed = 0.00 Round = 3 w1 = 0.4090 w2 = 0.6405 w3 = 0.4137 Value = -214561698.7466
## elapsed = 0.00 Round = 4 w1 = 0.8830 w2 = 0.9943 w3 = 0.3688 Value = -1552846530.5179
## elapsed = 0.00 Round = 5 w1 = 0.9405 w2 = 0.6557 w3 = 0.1524 Value = -560428652.5203
## elapsed = 0.00 Round = 6 w1 = 0.0456 w2 = 0.7085 w3 = 0.1388 Value = -11471892.0673
## elapsed = 0.00 Round = 7 w1 = 0.5281 w2 = 0.5441 w3 = 0.2330 Value = -93150457.4806
## elapsed = 0.00 Round = 8 w1 = 0.8924 w2 = 0.5941 w3 = 0.4660 Value = -907301041.4723
## elapsed = 0.00 Round = 9 w1 = 0.5514 w2 = 0.2892 w3 = 0.2660 Value = -11356600.7449
## elapsed = 0.00 Round = 10 w1 = 0.4566 w2 = 0.1471 w3 = 0.8578 Value = -213034020.6426
## elapsed = 0.00 Round = 11 w1 = 0.9568 w2 = 0.9630 w3 = 0.0458 Value = -932554747.0758
## elapsed = 0.00 Round = 12 w1 = 0.4533 w2 = 0.9023 w3 = 0.4422 Value = -636537927.4026
## elapsed = 0.00 Round = 13 w1 = 0.6776 w2 = 0.6907 w3 = 0.7989 Value = -1362357606.0057
## elapsed = 0.00 Round = 14 w1 = 0.5726 w2 = 0.7955 w3 = 0.1219 Value = -240100071.0720
## elapsed = 0.00 Round = 15 w1 = 0.1029 w2 = 0.0246 w3 = 0.5609 Value = -97040726.7633
## elapsed = 0.00 Round = 16 w1 = 0.8998 w2 = 0.4778 w3 = 0.2065 Value = -341233940.9660
## elapsed = 0.00 Round = 17 w1 = 0.2461 w2 = 0.7585 w3 = 0.1275 Value = -17444831.2329
## elapsed = 0.00 Round = 18 w1 = 0.0421 w2 = 0.2164 w3 = 0.7533 Value = -138639.9912
## elapsed = 0.00 Round = 19 w1 = 0.3279 w2 = 0.3182 w3 = 0.8950 Value = -292840156.2228
## elapsed = 0.00 Round = 20 w1 = 0.9545 w2 = 0.2316 w3 = 0.3745 Value = -314263621.5192
## elapsed = 0.00 Round = 21 w1 = 1.0000 w2 = 0.0000 w3 = 0.0000 Value = 3.7129
## elapsed = 0.00 Round = 22 w1 = 0.0000 w2 = 0.0000 w3 = 1.0000 Value = 16.2381
## elapsed = 0.00 Round = 23 w1 = 0.0000 w2 = 0.9994 w3 = 0.0000 Value = -374.2826
## elapsed = 0.00 Round = 24 w1 = 0.6871 w2 = 0.0000 w3 = 0.3076 Value = -28791.8047
## elapsed = 0.00 Round = 25 w1 = 0.6018 w2 = 0.3872 w3 = 0.0000 Value = -121085.4959
## elapsed = 0.00 Round = 26 w1 = 0.0022 w2 = 0.7501 w3 = 0.2644 Value = -278397.5709
## elapsed = 0.01 Round = 27 w1 = 0.2083 w2 = 0.0074 w3 = 0.7750 Value = -87021.5536
## elapsed = 0.00 Round = 28 w1 = 0.6844 w2 = 0.1581 w3 = 0.1652 Value = -58926.3506
## elapsed = 0.00 Round = 29 w1 = 0.7787 w2 = 0.2222 w3 = 0.0000 Value = -685.6368
## elapsed = 0.00 Round = 30 w1 = 0.8910 w2 = 0.0540 w3 = 0.0551 Value = -0.4746
##
## Best Parameters Found:
## Round = 22 w1 = 0.0000 w2 = 0.0000 w3 = 1.0000 Value = 16.2381
## 1: 618.94 sec elapsed
Let’s compare the optimum Sharpe Ratio from Bayesian Optimization with another algorithm: Particle Swarm Optimization. If you are unfamiliar with the method, you can visit my post6.
Let’s redefine the fitness function to suit the PSO from pso package.
fitness <- function(x){
# Assign weight for each stocks
weight_stock <- numeric()
for (i in 1:n_distinct(nyse$symbol)) {
weight_stock[i] <- x[i]
}
# Calculate the numerator
f1 <- numeric()
for (i in 1:n_distinct(nyse$symbol)) {
f1[i] <- weight_stock[i]*mean_stock$mean[i]
}
# Calculate the denominator
f2 <- numeric()
for (i in 1:n_distinct(nyse$symbol)) {
f3 <- numeric()
for (j in 1:n_distinct(nyse$symbol)) {
f3[j] <- weight_stock[i]*weight_stock[j]*nyse_cov[i,j]
}
f2[i] <- sum(f3)
}
# Calculate Fitness Value
fitness <- (sum(f1)-rf)/sum(f2)
# Penalize Constraint Violation
fitness <- fitness - 1e9 * (round(sum(weight_stock),10)-1)^2
return(fitness)
}Let’s run the PSO Algorithm. PSO will run for 10,000 iterations with swarm size of 100. If in 500 iterations there is no improvement on the fitness value, the algorithm will stop.
tictoc::tic()
set.seed(123)
pso_finance <- psoptim(par = rep(NA,3), fn = function(x){-fitness(x)},
lower = rep(0,3), upper = rep(1,3),
control = list(maxit = 10000, s = 100, maxit.stagnate = 500))
pso_finance## $par
## [1] 0.18286098 0.01961205 0.79752697
##
## $value
## [1] -19.2006
##
## $counts
## function iteration restarts
## 107700 1077 0
##
## $convergence
## [1] 4
##
## $message
## [1] "Maximal number of iterations without improvement reached"
## 16.69 sec elapsed
The solutions has Sharpe Ratio of 19.201.
Let’s check the total weight
## [1] 1
Based on PSO, here is how your asset should be distributed.
data.frame(stock = unique(nyse$symbol),
weight = pso_finance$par) %>%
arrange(desc(weight)) %>%
mutate(weight = percent(weight, accuracy = 0.01)) %>%
left_join(securities, by = "stock") %>%
select(stock, Security, everything())For this problem, PSO works better than Bayesian Optimization, indicated by the optimum fitness value. However, we only ran 40 function evalutions (20 from samples, 20 from iterations) with Bayesian Optimization, compared to PSO, which run more than 1000 evaluations. The trade-off is Bayesian Optimization ran slower than PSO, since the function evaluation is cheap. We will try in more complex problem via deep learning to see if the trade-off don’t change.
We will try to classify whether a user will give a game an above average score based on the content of the reviews. We will use the neural network model. Reviews will be extracted using text mining approach. On this problem, we will optimize the hyper-parameter of the neural network. This problem is based on my previous post7.
The dataset is user reviews of 100 best PC games from metacritic website. I already scraped the data, which you can download here .
Since we will use keras to build the neural network architecture, we will set the environment first.
We want to clean the text by removing url and any word elongation. We will replace “?” with “questionmark” and “!” with “exclamationmark” to see if these characters can be useful in our analysis, etc.
question <- rx() %>%
rx_find(value = "?") %>%
rx_one_or_more()
exclamation <- rx() %>%
rx_find(value = "!") %>%
rx_one_or_more()
punctuation <- rx_punctuation()
number <- rx_digit()
dollar <- rx() %>%
rx_find("$")game_review <- game_review %>%
mutate(
text_clean = review %>%
replace_url() %>%
replace_html() %>%
replace_contraction() %>%
replace_word_elongation() %>%
str_replace_all(pattern = question, replacement = " questionmark ") %>%
str_replace_all(pattern = exclamation, replacement = " exclamationmark ") %>%
str_remove_all(pattern = punctuation) %>%
str_remove_all(pattern = number) %>%
str_remove_all(pattern = dollar) %>%
str_to_lower() %>%
str_squish()
)
game_review